package edu.ynu.se.xiecheng.achitectureclass.service;


import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@Service
public class UserService extends LogicService<UserDao, User, Long>{

    public UserService(@Autowired UserDao userDao) {
        super(userDao);
    }


    @Transactional
    public Boolean registerUser(User user) {
        if (user == null || user.getPassword() == null) {
            throw new IllegalArgumentException("User or password cannot be null");
        }
        user.setPassword(hashPassword(user.getPassword()));
        return super.POST(user) != null;
    }

    @Transactional
    public Boolean loginUser(String userName, String password) {
        User user = super.GET((long) Math.toIntExact(super.getDAO().findUserByUserName(userName).getId()));
        if (user == null) {
            return false;
        }
        return hashPassword(password).equals(user.getPassword());
    }

    // SHA-512 编码
    private String hashPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-512");
            byte[] encodedhash = digest.digest(password.getBytes());
            return bytesToHex(encodedhash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not hash password", e);
        }
    }

    private String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
